package com.dongshan.myregistry.service.impl;

import com.dongshan.myregistry.beans.InstanceMeta;
import com.dongshan.myregistry.service.RegisterService;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * RegisterService 默认实现
 */
public class MyRegistryService implements RegisterService {
    private static final MultiValueMap<String,InstanceMeta> INSTANCES = new LinkedMultiValueMap<>();

    private static final Logger log = LoggerFactory.getLogger(MyRegistryService.class);


    private static final Map<String,Long> VERSIONS = Maps.newConcurrentMap();
    private static final AtomicLong VERSION = new AtomicLong(0);
    public static final Map<String,Long> TIMESTAMPS = Maps.newConcurrentMap();

    /**
     * 实现服务注册
     * @param server
     * @param instance
     * @return
     */
    @Override
    public InstanceMeta register(String server, InstanceMeta instance) {
        List<InstanceMeta> instanceMetas = INSTANCES.get(server);
        // 1.如果服务存在
        if(Objects.nonNull(instanceMetas) && !instanceMetas.isEmpty()){
            // 1.1 如果服务已经存在，将服务状态设置为true
            log.info("==> already exists server:{},instance：{}",server,instance);
            if(instanceMetas.contains(instance)){
                instance.setStatus(true);
                return instance;
            }
        }
        // 2.如果服务不存在，将服务加入到列表中
        log.info("==> register server:{},instance：{}",server,instance);
        instance.setStatus(true);
        INSTANCES.add(server,instance);
        // 3.更新时间戳和版本号
        renew(instance,server);
        updateVersion(server);
        return instance;
    }

    @Override
    public InstanceMeta unregister(String server, InstanceMeta instance) {
        List<InstanceMeta> instanceMetas = INSTANCES.get(server);
        // 1.如果服务不存在
        if(Objects.isNull(instanceMetas) || instanceMetas.isEmpty()){
            // 1.1 如果服务已经存在，将服务状态设置为false
            log.debug("==> not exist server:{},instance：{}",server,instance);
            instance.setStatus(false);
            return instance;
        }
        // 2.如果服务存在，将服务移出列表
        log.debug("==> unregister server:{},instance：{}",server,instance);
        instanceMetas.removeIf(k->k.equals(instance));
        // 3.更新时间戳和版本号
        renew(instance,server);
        updateVersion(server);
        return instance;
    }

    @Override
    public List<InstanceMeta> findAllInstances(String server) {
        return INSTANCES.get(server);
    }

    @Override
    public Long version(String server) {
        return VERSIONS.get(server);
    }

    @Override
    public Map<String, Long> versions(String... servers) {
        return Arrays.stream(servers).collect(Collectors.toMap(k->k,VERSIONS::get,(v1,v2)->v2));
    }


    /**
     * 更新服务的版本
     * @param server
     * @return
     */
    public Long updateVersion(String server){
        return VERSIONS.put(server,VERSION.getAndIncrement());
    }

    @Override
    public Long renew(InstanceMeta instance, String... servers) {
        long now = System.currentTimeMillis();
        for(String server:servers){
            String serverAndInstance =Strings.lenientFormat("%s@%s",server,instance.toUrl());
            TIMESTAMPS.put(serverAndInstance,now);
        }
        return now;
    }

}
